<template>
  <div class="app-container">
    <!-- 过滤栏 -->
    <filter-container 
      ref="filterContainer"
      :total="total" 
      search-placeholder="搜索提问单号、订单/客户信息、问答概要、销售"
      :show-delete-filter="false"
      @search="handleFilter"
    >
      <template #filter-items>
        <el-select
          v-model="listQuery.time_slot"
          placeholder="时间段"
          clearable
          class="filter-item"
          style="width: 150px"
          @change="handleTimeSlotChange"
        >
          <el-option label="9:30-10:00" value="09:30-10:00" />
          <el-option label="11:30-12:00" value="11:30-12:00" />
          <el-option label="13:30-14:00" value="13:30-14:00" />
          <el-option label="15:30-16:00" value="15:30-16:00" />
          <el-option label="17:30-18:00" value="17:30-18:00" />
        </el-select>
        
        <el-input
          v-model="listQuery.user"
          placeholder="用户/创建人"
          clearable
          class="filter-item"
          style="width: 120px"
          @input="handleUserChange"
        />
      </template>
      
      <template #action-buttons>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          新增
        </el-button>
        <el-button
          class="filter-item"
          type="info"
          icon="el-icon-data-analysis"
          @click="handleStatistics"
        >
          统计
        </el-button>
      </template>
      
      <template #selection-info>
        <span v-if="multipleSelection.length > 0" class="selection-info">
          已选择 <span class="selection-count">{{ multipleSelection.length }}</span> 条数据
        </span>
      </template>
    </filter-container>
    
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <shipping-table-columns
        type="order-qa"
        :show-actions="true"
        :show-edit="true"
        :show-delete="true"
        @edit="handleEdit"
        @delete="handleDeleteWarning"
      />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      :page-sizes="[20, 50, 100, 200]"
      @pagination="handlePaginationChange"
      class="pagination-container"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提问单号" prop="question_no">
              <el-input v-model="temp.question_no" placeholder="Q250612345678" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间段" prop="time_slot">
              <el-select v-model="temp.time_slot" placeholder="请选择时间段" style="width: 100%">
                <el-option label="9:30-10:00" value="09:30-10:00" />
                <el-option label="11:30-12:00" value="11:30-12:00" />
                <el-option label="13:30-14:00" value="13:30-14:00" />
                <el-option label="15:30-16:00" value="15:30-16:00" />
                <el-option label="17:30-18:00" value="17:30-18:00" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        
        <el-form-item label="订单信息" prop="customer_info">
          <el-input v-model="temp.customer_info" placeholder="本地用FS，转运用CW" />
        </el-form-item>
        
        <el-form-item label="问答概要" prop="question_summary">
          <el-input
            v-model="temp.question_summary"
            type="textarea"
            :rows="3"
            placeholder="问答的简要描述，非必填"
          />
        </el-form-item>
        
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售" prop="sales_person">
              <el-input v-model="temp.sales_person" placeholder="多个销售用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog
      title="订单问答统计"
      :visible.sync="statisticsDialogVisible"
      width="600px"
    >
      <div v-if="statisticsData">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="statistics-card">
              <div slot="header">
                <span>总体统计</span>
              </div>
              <div class="statistics-content">
                <p>总记录数：<strong>{{ statisticsData.total_records }}</strong></p>
                <p>总数量：<strong>{{ statisticsData.total_quantity }}</strong></p>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="statistics-card">
              <div slot="header">
                <span>用户统计</span>
              </div>
              <div class="statistics-content">
                <div v-for="user in statisticsData.user_stats" :key="user.created_by__username" class="user-item">
                  <span>{{ user.created_by__username || '未知' }}：{{ user.count }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-card class="statistics-card" style="margin-top: 20px;">
          <div slot="header">
            <span>时间段统计</span>
          </div>
          <div class="statistics-content">
            <el-row :gutter="20">
              <el-col :span="8" v-for="(stat, key) in statisticsData.time_slot_stats" :key="key">
                <div class="time-slot-item">
                  <p><strong>{{ stat.display }}</strong></p>
                  <p>记录数：{{ stat.count }}</p>
                  <p>数量：{{ stat.quantity }}</p>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ShippingTableColumns from '@/components/ShippingTableColumns'
import FilterContainer from './components/FilterContainer.vue'
import Pagination from '@/components/Pagination'
import { fetchOrderQAList, createOrderQA, updateOrderQA, deleteOrderQA, getOrderQAStatistics } from '@/api/shipping'

export default {
  name: 'OrderQA',
  components: {
    ShippingTableColumns,
    FilterContainer,
    Pagination
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        search: '',
        time_slot: '',
        user: '',
        start_date: '',
        end_date: ''
      },
      multipleSelection: [],
      
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '',
      temp: {
        id: undefined,
        question_no: '',
        customer_info: '',
        question_summary: '',
        sales_person: '',
        time_slot: ''
      },
      rules: {
        question_no: [
          { required: true, message: '请输入提问单号', trigger: 'blur' },
          { pattern: /^Q\d+$/, message: '提问单号必须以Q开头', trigger: 'blur' }
        ],
        customer_info: [
          { required: true, message: '请输入客户信息', trigger: 'blur' }
        ],
        question_summary: [
          { required: false, message: '请输入问答概要', trigger: 'blur' }
        ],
        sales_person: [
          { required: false, message: '请输入销售信息', trigger: 'blur' }
        ],
        time_slot: [
          { required: true, message: '请选择时间段', trigger: 'change' }
        ]
      },
      
      // 统计对话框
      statisticsDialogVisible: false,
      statisticsData: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchOrderQAList(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    
    handleFilter(params) {
      this.listQuery.page = 1
      
      // 处理日期范围
      if (params.dateRange && params.dateRange.length === 2) {
        this.listQuery.start_date = params.dateRange[0]
        this.listQuery.end_date = params.dateRange[1]
      } else {
        delete this.listQuery.start_date
        delete this.listQuery.end_date
      }
      
      // 更新查询参数
      this.listQuery = {
        ...this.listQuery,
        search: params.keyword || this.listQuery.search
      }
      
      this.getList()
    },
    
    handleTimeSlotChange() {
      this.handleFilter({})
    },
    
    handleUserChange() {
      this.handleFilter({})
    },
    
    
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    
    handlePaginationChange(page, pageSize) {
      this.listQuery.page = page
      this.listQuery.page_size = pageSize
      this.getList()
    },
    
    handlePagination(data) {
      this.listQuery.page = data.page
      this.listQuery.page_size = data.limit
      this.getList()
    },
    
    handleCreate() {
      this.resetTemp()
      this.dialogTitle = '新增订单问答'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    handleEdit(row) {
      this.temp = Object.assign({}, row)
      this.dialogTitle = '编辑订单问答'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    handleDeleteWarning(row) {
      this.$confirm(
        `警告：删除后数据将永久丢失，无法恢复！`, 
        '删除确认', 
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error',
          customClass: 'delete-confirm-dialog'
        }
      ).then(() => {
        deleteOrderQA(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录')
        return
      }
      
      this.$confirm(
        `警告：删除后数据将永久丢失，无法恢复！`, 
        '批量删除确认', 
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error',
          customClass: 'delete-confirm-dialog'
        }
      ).then(() => {
        const deletePromises = this.multipleSelection.map(item => deleteOrderQA(item.id))
        Promise.all(deletePromises).then(() => {
          this.$message.success(`批量删除成功，共删除 ${this.multipleSelection.length} 条记录`)
          this.getList()
        })
      })
    },
    
    handleSave() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = !!this.temp.id
          const api = isEdit ? updateOrderQA : createOrderQA
          
          api(this.temp).then(() => {
            this.$message.success(isEdit ? '更新成功' : '创建成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    
    handleStatistics() {
      getOrderQAStatistics(this.listQuery).then(response => {
        this.statisticsData = response.data
        this.statisticsDialogVisible = true
      })
    },
    
    resetTemp() {
      this.temp = {
        id: undefined,
        question_no: '',
        customer_info: '',
        question_summary: '',
        sales_person: '',
        time_slot: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/shipping-common.scss';
.statistics-card {
  margin-bottom: 20px;
}

.statistics-content {
  padding: 10px 0;
}

.user-item {
  margin-bottom: 8px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.time-slot-item {
  text-align: center;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.time-slot-item p {
  margin: 5px 0;
}

.el-message-box__content {
  white-space: pre-line !important;
  color: #f56c6c !important;
  font-weight: bold !important;
}
</style>
